package com.EAsystem.controller.student;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.*;
import com.EAsystem.entity.Class;
import com.EAsystem.service.AnnouncementService;
import com.EAsystem.service.CourseService;
import com.EAsystem.service.CourseSelectionService;
import com.EAsystem.service.GradeService;
import com.EAsystem.service.HomeworkService;
import com.EAsystem.service.HomeworkSubmissionService;
import com.EAsystem.service.StudentService;
import com.EAsystem.service.AttendanceService;
import com.EAsystem.service.LeaveService;
import com.EAsystem.service.EvaluationService;
import com.EAsystem.service.UserService;
import com.EAsystem.service.CollegeService;
import com.EAsystem.service.MajorService;
import com.EAsystem.service.ClassService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.FileSystemResource;

import jakarta.servlet.http.HttpSession;

import java.util.*;
import java.io.IOException;

@Controller
@RequestMapping("/student")
@RequireRole({3}) // 只有学生可以访问
public class StudentController {

    @Autowired
    private AnnouncementService announcementService;
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private CourseSelectionService courseSelectionService;
    
    @Autowired
    private GradeService gradeService;
    
    @Autowired
    private AttendanceService attendanceService;
    
    @Autowired
    private CollegeService collegeService;
    
    @Autowired
    private MajorService majorService;
    
    @Autowired
    private ClassService classService;
    
    @Autowired
    private EvaluationService evaluationService;
    
    @Autowired
    private LeaveService leaveService;
    
    @Autowired
    private HomeworkSubmissionService homeworkSubmissionService;

    @Autowired
    private HomeworkService homeworkService;

    /**
     * 学生首页
     */
    @GetMapping("/home")
    public String studentHome(Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/home";
            }
            
            // 获取教务通知（最新5条）
            List<Announcement> academicNotifications = announcementService.findByTypeOne();
            if (academicNotifications != null && academicNotifications.size() > 5) {
                academicNotifications = academicNotifications.subList(0, 5);
            }
            
            // 获取考试安排（最新5条）
            List<Announcement> examNotifications = announcementService.findByTypeTwo();
            if (examNotifications != null && examNotifications.size() > 5) {
                examNotifications = examNotifications.subList(0, 5);
            }
            
            // 获取教室安排（最新5条）
            List<Announcement> classroomNotifications = announcementService.findByTypeThree();
            if (classroomNotifications != null && classroomNotifications.size() > 5) {
                classroomNotifications = classroomNotifications.subList(0, 5);
            }
            
            // 获取学生的选课信息统计
            List<CourseSelection> myCourses = courseSelectionService.findByStudentId(currentStudent.getId());
            int totalCourses = myCourses != null ? myCourses.size() : 0;
            
            // 获取学生的成绩信息统计 - 使用条件查询
            Grade searchGrade = new Grade();
            Student searchStudent = new Student();
            searchStudent.setId(currentStudent.getId());
            searchGrade.setStudent(searchStudent);
            List<Grade> myGrades = gradeService.findByCondition(searchGrade);
            int totalGrades = myGrades != null ? myGrades.size() : 0;
            
            // 计算总学分
            int totalCredits = 0;
            if (myCourses != null) {
                for (CourseSelection cs : myCourses) {
                    if (cs.getCourse() != null && cs.getCourse().getCredits() != null) {
                        totalCredits += cs.getCourse().getCredits();
                    }
                }
            }
            
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("academicNotifications", academicNotifications != null ? academicNotifications : new ArrayList<>());
            model.addAttribute("examNotifications", examNotifications != null ? examNotifications : new ArrayList<>());
            model.addAttribute("classroomNotifications", classroomNotifications != null ? classroomNotifications : new ArrayList<>());
            model.addAttribute("totalCourses", totalCourses);
            model.addAttribute("totalGrades", totalGrades);
            model.addAttribute("totalCredits", totalCredits);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "加载首页信息失败：" + e.getMessage());
        }
        
        return "student/home";
    }

    /**
     * 个人信息页面
     */
    @GetMapping("/profile")
    public String profile(Model model, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            model.addAttribute("currentStudent", currentStudent);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取个人信息失败：" + e.getMessage());
        }
        
        return "student/profile";
    }

    /**
     * 修改密码页面
     */
    @GetMapping("/changePassword")
    public String changePasswordPage() {
        return "student/change_password";
    }

    /**
     * 修改密码处理
     */
    @PostMapping("/changePassword")
    @ResponseBody
    public Map<String, Object> changePassword(@RequestParam String oldPassword,
                                             @RequestParam String newPassword,
                                             @RequestParam String confirmPassword,
                                             HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            // 验证新密码和确认密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                result.put("success", false);
                result.put("message", "新密码和确认密码不一致");
                return result;
            }
            
            // 验证旧密码是否正确
            User user = userService.findById(currentUser.getId());
            if (user == null || !oldPassword.equals(user.getPassword())) {
                result.put("success", false);
                result.put("message", "原密码错误");
                return result;
            }
            
            // 更新密码
            user.setPassword(newPassword);
            boolean success = userService.update(user);
            
            if (success) {
                result.put("success", true);
                result.put("message", "密码修改成功");
            } else {
                result.put("success", false);
                result.put("message", "密码修改失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "修改密码失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 教务通知页面
     */
    @GetMapping("/notifications/academic")
    public String academicNotifications(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "5") int size,
                                       @RequestParam(required = false) String titleSearch,
                                       Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<Announcement> pageInfo;
            if (titleSearch != null && !titleSearch.trim().isEmpty()) {
                Announcement announcement = new Announcement();
                announcement.setTitle(titleSearch.trim());
                announcement.setType(1); // 教务通知类型
                pageInfo = announcementService.findByConditionPage(announcement, page, size);
            } else {
                pageInfo = announcementService.findByTypeOneWithPage(page, size); // 1表示教务通知
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            // 修正属性名，使用notifications而不是announcements
            model.addAttribute("notifications", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("titleSearch", titleSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("notifications", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("titleSearch", titleSearch);
            model.addAttribute("error", "加载教务通知失败：" + e.getMessage());
        }
        
        return "student/academic_notifications";
    }

    /**
     * 考试安排页面
     */
    @GetMapping("/notifications/exam")
    public String examNotifications(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "5") int size,
                                   @RequestParam(required = false) String titleSearch,
                                   Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<Announcement> pageInfo;
            if (titleSearch != null && !titleSearch.trim().isEmpty()) {
                Announcement announcement = new Announcement();
                announcement.setTitle(titleSearch.trim());
                announcement.setType(2); // 考试安排类型
                pageInfo = announcementService.findByConditionPage(announcement, page, size);
            } else {
                pageInfo = announcementService.findByTypeTwoWithPage(page, size); // 2表示考试安排
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            // 修正属性名，使用notifications而不是announcements
            model.addAttribute("notifications", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("titleSearch", titleSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("notifications", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("titleSearch", titleSearch);
            model.addAttribute("error", "加载考试安排失败：" + e.getMessage());
        }
        
        return "student/exam_notifications";
    }

    /**
     * 教室安排页面
     */
    @GetMapping("/notifications/classroom")
    public String classroomNotifications(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "5") int size,
                                       @RequestParam(required = false) String titleSearch,
                                       Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<Announcement> pageInfo;
            if (titleSearch != null && !titleSearch.trim().isEmpty()) {
                Announcement announcement = new Announcement();
                announcement.setTitle(titleSearch.trim());
                announcement.setType(3); // 教室安排类型
                pageInfo = announcementService.findByConditionPage(announcement, page, size);
            } else {
                pageInfo = announcementService.findByTypeThreeWithPage(page, size); // 3表示教室安排
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }

            model.addAttribute("notifications", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("titleSearch", titleSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("notifications", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("titleSearch", titleSearch);
            model.addAttribute("error", "加载教室安排失败：" + e.getMessage());
        }
        
        return "student/classroom_notifications";
    }

    /**
     * 学院管理页面
     */
    @GetMapping("/college")
    public String collegeList(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "5") int size,
                             @RequestParam(required = false) String nameSearch,
                             Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<College> pageInfo;
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                College college = new College();
                college.setName(nameSearch.trim());
                pageInfo = collegeService.findByNameWithPage(college, page, size);
            } else {
                pageInfo = collegeService.findAllByPage(page, size);
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            model.addAttribute("colleges", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", nameSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("colleges", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "加载学院信息失败：" + e.getMessage());
        }
        
        return "student/college";
    }

    /**
     * 专业管理页面
     */
    @GetMapping("/major")
    public String majorList(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size,
                           @RequestParam(required = false) String nameSearch,
                           Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<Major> pageInfo;
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                Major major = new Major();
                major.setName(nameSearch.trim());
                pageInfo = majorService.findByNamePage(major, page, size);
            } else {
                pageInfo = majorService.findAllByPage(page, size);
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            model.addAttribute("majors", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", nameSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("majors", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "加载专业信息失败：" + e.getMessage());
        }
        
        return "student/major";
    }

    /**
     * 班级管理页面
     */
    @GetMapping("/class")
    public String classList(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size,
                           @RequestParam(required = false) String nameSearch,
                           Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息（用于个人中心模态框）
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser != null) {
                Student currentStudent = studentService.findByUserId(currentUser.getId());
                model.addAttribute("currentStudent", currentStudent);
            }
            
            PageInfo<com.EAsystem.entity.Class> pageInfo;
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                pageInfo = classService.findByNamePage(nameSearch.trim(), page, size);
            } else {
                pageInfo = classService.findAllByPage(page, size);
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            model.addAttribute("classes", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", nameSearch);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("classes", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "加载班级信息失败：" + e.getMessage());
        }
        
        return "student/class";
    }

    /**
     * 课程管理页面（选课界面）
     */
    @GetMapping("/courses")
    public String courseList(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "5") int size,
                            @RequestParam(required = false) String nameSearch,
                            Model model,
                            HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/courses";
            }
            
            PageInfo<Course> pageInfo;
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                Course course = new Course();
                course.setName(nameSearch.trim());
                course.setStatus(1); // 只显示启用的课程
                pageInfo = courseService.findByConditionPageInfo(course, page, size);
            } else {
                // 创建查询条件，只显示启用的课程
                Course statusCourse = new Course();
                statusCourse.setStatus(1);
                pageInfo = courseService.findByConditionPageInfo(statusCourse, page, size);
            }
            
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            // 获取学生的选课记录，用于判断是否已选课
            List<CourseSelection> studentCourseSelections = courseSelectionService.findByStudentId(currentStudent.getId());
            
            model.addAttribute("courses", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("studentCourseSelections", studentCourseSelections);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("courses", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "加载课程信息失败：" + e.getMessage());
        }
        
        return "student/courses";
    }

    /**
     * 选课操作
     */
    @PostMapping("/courses/select")
    @ResponseBody
    public Map<String, Object> selectCourse(@RequestParam Long courseId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 检查课程是否存在且启用
            Course course = courseService.findById(courseId);
            if (course == null) {
                result.put("success", false);
                result.put("message", "课程不存在");
                return result;
            }
            
            if (course.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "该课程未开放选课");
                return result;
            }
            
            // 检查是否已经选过该课程
            CourseSelection existingSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), courseId);
            if (existingSelection != null) {
                if (existingSelection.getStatus() == 1) {
                    result.put("success", false);
                    result.put("message", "您已经选择了该课程");
                    return result;
                } else if (existingSelection.getStatus() == 0) {
                    result.put("success", false);
                    result.put("message", "该课程选课申请正在审核中");
                    return result;
                } else if (existingSelection.getStatus() == 2) {
                    // 已退选的课程可以重新选择
                    // 检查课程是否已满
                    List<CourseSelection> courseSelections = courseSelectionService.findByCourseId(courseId);
                    long selectedCount = courseSelections.stream().filter(cs -> cs.getStatus() == 1).count();
                    if (selectedCount >= course.getMaxStudents()) {
                        result.put("success", false);
                        result.put("message", "该课程人数已满");
                        return result;
                    }
                    
                    // 更新已退选记录的状态为已选课
                    String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
                    int updateResult = courseSelectionService.updateStatus(Long.valueOf(existingSelection.getId()), 1, currentTime);
                    if (updateResult > 0) {
                        result.put("success", true);
                        result.put("message", "重新选课成功");
                    } else {
                        result.put("success", false);
                        result.put("message", "重新选课失败，请重试");
                    }
                    return result;
                }
            }
            
            // 检查课程是否已满
            List<CourseSelection> courseSelections = courseSelectionService.findByCourseId(courseId);
            long selectedCount = courseSelections.stream().filter(cs -> cs.getStatus() == 1).count();
            if (selectedCount >= course.getMaxStudents()) {
                result.put("success", false);
                result.put("message", "该课程人数已满");
                return result;
            }
            
            // 创建选课记录
            CourseSelection courseSelection = new CourseSelection();
            courseSelection.setStudent(currentStudent);
            courseSelection.setCourse(course);
            courseSelection.setStatus(1); // 直接设为已选课状态
            
            int addResult = courseSelectionService.add(courseSelection);
            if (addResult > 0) {
                result.put("success", true);
                result.put("message", "选课成功");
            } else {
                result.put("success", false);
                result.put("message", "选课失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "选课失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 退课操作
     */
    @PostMapping("/courses/drop")
    @ResponseBody
    public Map<String, Object> dropCourse(@RequestParam Long courseId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 检查选课记录是否存在
            CourseSelection existingSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), courseId);
            if (existingSelection == null) {
                result.put("success", false);
                result.put("message", "您未选择该课程");
                return result;
            }
            
            if (existingSelection.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "只能退选已选课程");
                return result;
            }

            int deleteResult = courseSelectionService.delete(existingSelection.getId());
            
            if (deleteResult > 0) {
                result.put("success", true);
                result.put("message", "退课成功，该课程已从您的选课列表中移除");
            } else {
                result.put("success", false);
                result.put("message", "退课失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "退课失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 我的选课管理页面
     */
    @GetMapping("/my-courses")
    public String myCourses(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size,
                           @RequestParam(required = false) String nameSearch,
                           Model model,
                           HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/my-courses";
            }
            
            // 获取学生的所有选课记录
            List<CourseSelection> allSelections = courseSelectionService.findByStudentId(currentStudent.getId());
            if (allSelections == null) {
                allSelections = new ArrayList<>();
            }
            
            // 过滤有效的选课记录（只显示待审核和已选课的记录）
            List<CourseSelection> validSelections = new ArrayList<>();
            for (CourseSelection selection : allSelections) {
                // 只显示状态为0（待审核）和1（已选课）的记录
                if (selection.getStatus() == 0 || selection.getStatus() == 1) {
                    validSelections.add(selection);
                }
            }
            
            // 如果有课程名称搜索条件，进行过滤
            List<CourseSelection> filteredSelections = validSelections;
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                filteredSelections = new ArrayList<>();
                for (CourseSelection selection : validSelections) {
                    if (selection.getCourse() != null && 
                        selection.getCourse().getName() != null && 
                        selection.getCourse().getName().contains(nameSearch.trim())) {
                        filteredSelections.add(selection);
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredSelections.size());
            List<CourseSelection> pageSelections = new ArrayList<>();
            if (start < filteredSelections.size()) {
                pageSelections = filteredSelections.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) filteredSelections.size() / size);
            
            model.addAttribute("courseSelections", pageSelections);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", filteredSelections.size());
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("currentStudent", currentStudent);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("courseSelections", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "加载选课信息失败：" + e.getMessage());
        }
        
        return "student/my-courses";
    }



    /**
     * 提交课程评教（百分制，多项评分）
     */
    @PostMapping("/evaluation/submit")
    @ResponseBody
    public Map<String, Object> submitEvaluation(@RequestParam Long courseId,
                                               @RequestParam Integer teachingEffect,
                                               @RequestParam Integer teacherAttitude,
                                               @RequestParam Integer courseContent,
                                               @RequestParam Double averageScore,
                                               @RequestParam(required = false) String comment,
                                               HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 检查课程是否存在
            Course course = courseService.findById(courseId);
            if (course == null) {
                result.put("success", false);
                result.put("message", "课程不存在");
                return result;
            }
            
            // 检查学生是否已选择该课程且状态为已选课
            CourseSelection existingSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), courseId);
            if (existingSelection == null || existingSelection.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "您未选择该课程或课程状态不正确");
                return result;
            }
            
            // 检查是否已经评教过
            Evaluation existingEvaluation = evaluationService.getEvaluationByStudentAndCourse(currentStudent.getId().intValue(), courseId.intValue());
            if (existingEvaluation != null) {
                result.put("success", false);
                result.put("message", "您已经对该课程进行过评教");
                return result;
            }
            
            // 验证评分范围（1-5分转换为20-100分）
            if (teachingEffect < 1 || teachingEffect > 5 || 
                teacherAttitude < 1 || teacherAttitude > 5 || 
                courseContent < 1 || courseContent > 5) {
                result.put("success", false);
                result.put("message", "评分必须在1-5分之间");
                return result;
            }
            
            // 将5分制转换为100分制
            int finalScore = (int) Math.round(averageScore * 20);
            
            // 创建评教记录
            Evaluation evaluation = new Evaluation();
            evaluation.setStudent(currentStudent);
            evaluation.setCourse(course);
            evaluation.setTeacher(course.getTeacher());
            evaluation.setScore(finalScore); // 使用百分制分数
            
            // 构建详细评价内容
            StringBuilder detailedComment = new StringBuilder();
            detailedComment.append("教学效果评分: ").append(teachingEffect).append("分 (").append(teachingEffect * 20).append("分)\n");
            detailedComment.append("教师态度评分: ").append(teacherAttitude).append("分 (").append(teacherAttitude * 20).append("分)\n");
            detailedComment.append("课程内容评分: ").append(courseContent).append("分 (").append(courseContent * 20).append("分)\n");
            detailedComment.append("综合评分: ").append(String.format("%.1f", averageScore)).append("分 (").append(finalScore).append("分)\n");
            if (comment != null && !comment.trim().isEmpty()) {
                detailedComment.append("评价意见: ").append(comment.trim());
            }
            
            evaluation.setComment(detailedComment.toString());
            
            // 设置创建时间和更新时间
            Date currentTime = new java.util.Date();
            evaluation.setCreateTime(currentTime);
            evaluation.setUpdateTime(currentTime);
            
            boolean addResult = evaluationService.addEvaluation(evaluation);
            if (addResult) {
                result.put("success", true);
                result.put("message", "评教提交成功！感谢您的评价。");
            } else {
                result.put("success", false);
                result.put("message", "评教提交失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "评教失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 学生课程表页面
     */
    @GetMapping("/schedule")
    public String studentSchedule(Model model, HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/schedule";
            }
            
            // 获取学生的选课记录（状态为1，即已选课）
            List<CourseSelection> courseSelections = courseSelectionService.findByStudentId(currentStudent.getId());
            
            // 创建课程表数据结构：weekday -> period -> CourseSchedule
            Map<Integer, Map<Integer, CourseSchedule>> scheduleMap = new HashMap<>();
            
            // 初始化课程表结构（周一到周日，第1-5节）
            for (int weekday = 1; weekday <= 7; weekday++) {
                Map<Integer, CourseSchedule> daySchedule = new HashMap<>();
                for (int period = 1; period <= 5; period++) {
                    daySchedule.put(period, null);
                }
                scheduleMap.put(weekday, daySchedule);
            }
            
            // 填充课程表数据
            if (courseSelections != null) {
                for (CourseSelection selection : courseSelections) {
                    // 只处理已选课的记录
                    if (selection.getStatus() == 1 && selection.getCourse() != null) {
                        Course course = selection.getCourse();
                        
                        List<CourseSchedule> schedules = course.getCourseScheduleList();
                        
                        if (schedules != null) {
                            for (CourseSchedule schedule : schedules) {
                                schedule.setCourse(course);
                                
                                Integer weekday = schedule.getWeekday();
                                Integer period = schedule.getPeriod();

                                if (weekday != null && period != null && 
                                    weekday >= 1 && weekday <= 7 && 
                                    period >= 1 && period <= 5) {
                                    // 设置课程信息到课程表中
                                    scheduleMap.get(weekday).put(period, schedule);
                                }
                            }
                        }
                    }
                }
            }
            
            // 创建一个备用的简单列表，方便JSP渲染
            List<Map<String, Object>> scheduleList = new ArrayList<>();
            for (int weekday = 1; weekday <= 7; weekday++) {
                for (int period = 1; period <= 5; period++) {
                    CourseSchedule schedule = scheduleMap.get(weekday).get(period);
                    Map<String, Object> item = new HashMap<>();
                    item.put("weekday", weekday);
                    item.put("period", period);
                    if (schedule != null && schedule.getCourse() != null) {
                        item.put("hasSchedule", true);
                        item.put("courseName", schedule.getCourse().getName());
                        item.put("classroom", schedule.getClassroom());
                        item.put("teacherName", schedule.getCourse().getTeacher() != null && 
                                              schedule.getCourse().getTeacher().getUser() != null ? 
                                              schedule.getCourse().getTeacher().getUser().getRealName() : "未知教师");
                    } else {
                        item.put("hasSchedule", false);
                    }
                    scheduleList.add(item);
                }
            }
            
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("scheduleMap", scheduleMap);
            model.addAttribute("scheduleList", scheduleList);  // 备用数据结构
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "加载课程表失败：" + e.getMessage());
        }
        
        return "student/schedule";
    }

    /**
     * 成绩管理页面
     */
    @GetMapping("/grades")
    public String studentGrades(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "5") int size,
                               @RequestParam(required = false) String courseNameSearch,
                               Model model,
                               HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/grades";
            }

            Grade searchGrade = new Grade();
            Student searchStudent = new Student();
            searchStudent.setId(currentStudent.getId());
            searchGrade.setStudent(searchStudent);
            
            // 如果有课程名称搜索条件，添加到查询条件中
            if (courseNameSearch != null && !courseNameSearch.trim().isEmpty()) {
                Course searchCourse = new Course();
                searchCourse.setName(courseNameSearch.trim());
                searchGrade.setCourse(searchCourse);
            }
            
            // 分页查询成绩
            PageInfo<Grade> pageInfo = gradeService.findByConditionPage(searchGrade, page, size);
            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }
            
            // 计算平均分和统计信息
            double averageScore = 0.0;
            int totalCourses = 0;
            int passedCourses = 0;
            double totalCredits = 0.0;
            double weightedScore = 0.0;
            
            if (pageInfo.getList() != null && !pageInfo.getList().isEmpty()) {
                // 获取所有成绩计算统计信息
                List<Grade> allGrades = gradeService.findByCondition(searchGrade);
                if (allGrades != null) {
                    totalCourses = allGrades.size();
                    double scoreSum = 0.0;
                    
                    for (Grade grade : allGrades) {
                        if (grade.getTotalScore() != null) {
                            scoreSum += grade.getTotalScore();
                            if (grade.getTotalScore() >= 60) {
                                passedCourses++;
                            }
                        }
                        
                        // 计算加权平均分（考虑学分）
                        if (grade.getCourse() != null && grade.getCourse().getCredits() != null && grade.getTotalScore() != null) {
                            totalCredits += grade.getCourse().getCredits();
                            weightedScore += grade.getTotalScore() * grade.getCourse().getCredits();
                        }
                    }
                    
                    if (totalCourses > 0) {
                        averageScore = scoreSum / totalCourses;
                    }
                    
                    if (totalCredits > 0) {
                        weightedScore = weightedScore / totalCredits;
                    }
                }
            }
            
            model.addAttribute("grades", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("currentStudent", currentStudent);
            
            // 统计信息
            model.addAttribute("averageScore", Math.round(averageScore * 100) / 100.0);
            model.addAttribute("weightedScore", Math.round(weightedScore * 100) / 100.0);
            model.addAttribute("totalCourses", totalCourses);
            model.addAttribute("passedCourses", passedCourses);
            model.addAttribute("passRate", totalCourses > 0 ? Math.round((double) passedCourses / totalCourses * 100) : 0);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("grades", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("error", "加载成绩信息失败：" + e.getMessage());
        }
        
        return "student/grades";
    }

    /**
     * 网上评教页面
     */
    @GetMapping("/evaluation")
    public String studentEvaluation(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "5") int size,
                                   @RequestParam(required = false) String courseNameSearch,
                                   Model model,
                                   HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/evaluation";
            }
            
            // 获取学生的所有评教记录
            List<Evaluation> allEvaluations = evaluationService.getEvaluationsByStudentId(currentStudent.getId().intValue());
            if (allEvaluations == null) {
                allEvaluations = new ArrayList<>();
            }
            
            // 如果有课程名称搜索条件，进行过滤
            List<Evaluation> filteredEvaluations = allEvaluations;
            if (courseNameSearch != null && !courseNameSearch.trim().isEmpty()) {
                filteredEvaluations = new ArrayList<>();
                for (Evaluation evaluation : allEvaluations) {
                    if (evaluation.getCourse() != null && 
                        evaluation.getCourse().getName() != null && 
                        evaluation.getCourse().getName().contains(courseNameSearch.trim())) {
                        filteredEvaluations.add(evaluation);
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredEvaluations.size());
            List<Evaluation> pageEvaluations = new ArrayList<>();
            if (start < filteredEvaluations.size()) {
                pageEvaluations = filteredEvaluations.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) filteredEvaluations.size() / size);
            
            model.addAttribute("evaluations", pageEvaluations);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", filteredEvaluations.size());
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("currentStudent", currentStudent);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("evaluations", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("error", "加载评教信息失败：" + e.getMessage());
        }
        
        return "student/evaluation";
    }

    /**
     * 删除评教记录
     */
    @PostMapping("/evaluation/delete")
    @ResponseBody
    public Map<String, Object> deleteEvaluation(@RequestParam Integer evaluationId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 查询评教记录
            Evaluation evaluation = evaluationService.getEvaluationById(evaluationId);
            if (evaluation == null) {
                result.put("success", false);
                result.put("message", "评教记录不存在");
                return result;
            }
            
            // 验证权限 - 只能删除自己的评教记录
            if (!evaluation.getStudent().getId().equals(currentStudent.getId())) {
                result.put("success", false);
                result.put("message", "您没有权限删除该评教记录");
                return result;
            }
            
            // 删除评教记录
            boolean deleteResult = evaluationService.deleteEvaluationById(evaluationId);
            if (deleteResult) {
                result.put("success", true);
                result.put("message", "评教记录删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 请假管理页面
     */
    @GetMapping("/leave")
    public String studentLeave(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "5") int size,
                              @RequestParam(required = false) String courseNameSearch,
                              @RequestParam(required = false) Integer statusSearch,
                              Model model,
                              HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/leave";
            }
            
            // 获取学生的所有请假记录
            List<Leave> allLeaves = leaveService.getLeavesByStudentId(currentStudent.getId().intValue());
            if (allLeaves == null) {
                allLeaves = new ArrayList<>();
            }
            
            // 如果有搜索条件，进行过滤
            List<Leave> filteredLeaves = allLeaves;
            if ((courseNameSearch != null && !courseNameSearch.trim().isEmpty()) || statusSearch != null) {
                filteredLeaves = new ArrayList<>();
                for (Leave leave : allLeaves) {
                    boolean matchCourse = true;
                    boolean matchStatus = true;
                    
                    // 课程名称过滤
                    if (courseNameSearch != null && !courseNameSearch.trim().isEmpty()) {
                        matchCourse = leave.getCourse() != null && 
                                     leave.getCourse().getName() != null && 
                                     leave.getCourse().getName().contains(courseNameSearch.trim());
                    }
                    
                    // 状态过滤
                    if (statusSearch != null) {
                        matchStatus = leave.getStatus() != null && leave.getStatus().equals(statusSearch);
                    }
                    
                    if (matchCourse && matchStatus) {
                        filteredLeaves.add(leave);
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredLeaves.size());
            List<Leave> pageLeaves = new ArrayList<>();
            if (start < filteredLeaves.size()) {
                pageLeaves = filteredLeaves.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) filteredLeaves.size() / size);
            
            // 获取学生的选课信息
            List<CourseSelection> courseSelections = courseSelectionService.findByStudentId(currentStudent.getId());
            List<Course> availableCourses = new ArrayList<>();
            if (courseSelections != null) {
                for (CourseSelection cs : courseSelections) {
                    if (cs.getStatus() == 1 && cs.getCourse() != null) { // 只有已选课的课程
                        availableCourses.add(cs.getCourse());
                    }
                }
            }
            
            model.addAttribute("leaves", pageLeaves);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", filteredLeaves.size());
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("statusSearch", statusSearch);
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("availableCourses", availableCourses);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("leaves", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("statusSearch", statusSearch);
            model.addAttribute("availableCourses", new ArrayList<>());
            model.addAttribute("error", "加载请假信息失败：" + e.getMessage());
        }
        
        return "student/leave";
    }

    /**
     * 申请请假
     */
    @PostMapping("/leave/apply")
    @ResponseBody
    public Map<String, Object> applyLeave(@RequestParam Long courseId,
                                         @RequestParam String reason,
                                         @RequestParam String startTime,
                                         @RequestParam String endTime,
                                         HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 验证课程
            Course course = courseService.findById(courseId);
            if (course == null) {
                result.put("success", false);
                result.put("message", "课程不存在");
                return result;
            }
            
            // 验证学生是否已选择该课程
            CourseSelection courseSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), courseId);
            if (courseSelection == null || courseSelection.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "您未选择该课程或课程状态不正确");
                return result;
            }
            
            // 验证时间格式和逻辑
            if (startTime == null || startTime.trim().isEmpty() || 
                endTime == null || endTime.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "请假时间不能为空");
                return result;
            }
            
            // 验证原因
            if (reason == null || reason.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "请假原因不能为空");
                return result;
            }
            
            if (reason.trim().length() > 500) {
                result.put("success", false);
                result.put("message", "请假原因不能超过500字");
                return result;
            }
            
            // 创建请假申请
            Leave leave = new Leave();
            leave.setStudent(currentStudent);
            leave.setCourse(course);
            leave.setReason(reason.trim());
            leave.setStartTime(startTime.trim());
            leave.setEndTime(endTime.trim());
            
            boolean addResult = leaveService.addLeave(leave);
            if (addResult) {
                result.put("success", true);
                result.put("message", "请假申请提交成功，等待审核");
            } else {
                result.put("success", false);
                result.put("message", "请假申请提交失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "请假申请失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 撤销请假申请
     */
    @PostMapping("/leave/cancel")
    @ResponseBody
    public Map<String, Object> cancelLeave(@RequestParam Integer leaveId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 查询请假记录
            Leave leave = leaveService.getLeaveById(leaveId);
            if (leave == null) {
                result.put("success", false);
                result.put("message", "请假记录不存在");
                return result;
            }
            
            // 验证权限 - 只能撤销自己的请假申请
            if (!leave.getStudent().getId().equals(currentStudent.getId())) {
                result.put("success", false);
                result.put("message", "您没有权限撤销该请假申请");
                return result;
            }
            
            // 只能撤销待审核的请假申请
            if (leave.getStatus() == null || leave.getStatus() != 0) {
                result.put("success", false);
                result.put("message", "只能撤销待审核的请假申请");
                return result;
            }
            
            // 删除请假记录（撤销）
            boolean deleteResult = leaveService.deleteLeave(leaveId);
            if (deleteResult) {
                result.put("success", true);
                result.put("message", "请假申请撤销成功");
            } else {
                result.put("success", false);
                result.put("message", "撤销失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "撤销失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 作业提交管理页面
     */
    @GetMapping("/homework")
    public String homeworkPage(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "5") int size,
                              @RequestParam(required = false) String courseNameSearch,
                              Model model,
                              HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/homework";
            }
            
            // 获取学生已提交的作业记录
            List<HomeworkSubmission> allSubmissions = homeworkSubmissionService.getHomeworkSubmissionsByStudentId(currentStudent.getId());
            if (allSubmissions == null) {
                allSubmissions = new ArrayList<>();
            }
            
            // 如果有课程名称搜索条件，进行过滤
            List<HomeworkSubmission> filteredSubmissions = allSubmissions;
            if (courseNameSearch != null && !courseNameSearch.trim().isEmpty()) {
                filteredSubmissions = new ArrayList<>();
                for (HomeworkSubmission submission : allSubmissions) {
                    if (submission.getHomework() != null && 
                        submission.getHomework().getCourse() != null && 
                        submission.getHomework().getCourse().getName() != null && 
                        submission.getHomework().getCourse().getName().contains(courseNameSearch.trim())) {
                        filteredSubmissions.add(submission);
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredSubmissions.size());
            List<HomeworkSubmission> pageSubmissions = new ArrayList<>();
            if (start < filteredSubmissions.size()) {
                pageSubmissions = filteredSubmissions.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) filteredSubmissions.size() / size);
            
            // 获取学生的选课信息，用于新增作业提交
            List<CourseSelection> courseSelections = courseSelectionService.findByStudentId(currentStudent.getId());
            List<Course> availableCourses = new ArrayList<>();
            List<Homework> availableHomeworks = new ArrayList<>();
            
            if (courseSelections != null) {
                for (CourseSelection cs : courseSelections) {
                    if (cs.getStatus() == 1 && cs.getCourse() != null) { // 只有已选课的课程
                        availableCourses.add(cs.getCourse());
                        // 获取该课程的作业
                        List<Homework> courseHomeworks = homeworkService.getHomeworksByCourseId(cs.getCourse().getId());
                        if (courseHomeworks != null) {
                            for (Homework homework : courseHomeworks) {
                                // 检查学生是否已经提交过该作业
                                HomeworkSubmission existingSubmission = homeworkSubmissionService.getHomeworkSubmissionByHomeworkIdAndStudentId(homework.getId(), currentStudent.getId());
                                if (existingSubmission == null) {
                                    availableHomeworks.add(homework);
                                }
                            }
                        }
                    }
                }
            }
            
            model.addAttribute("homeworkSubmissions", pageSubmissions);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", filteredSubmissions.size());
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("availableCourses", availableCourses);
            model.addAttribute("availableHomeworks", availableHomeworks);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("homeworkSubmissions", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("availableCourses", new ArrayList<>());
            model.addAttribute("availableHomeworks", new ArrayList<>());
            model.addAttribute("error", "加载作业信息失败：" + e.getMessage());
        }
        
        return "student/homework";
    }

    /**
     * 提交作业
     */
    @PostMapping("/homework/submit")
    @ResponseBody
    public Map<String, Object> submitHomework(@RequestParam Long homeworkId,
                                             @RequestParam String content,
                                             @RequestParam(required = false) MultipartFile file,
                                             HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 验证作业是否存在
            Homework homework = homeworkService.getHomeworkById(homeworkId);
            if (homework == null) {
                result.put("success", false);
                result.put("message", "作业不存在");
                return result;
            }
            
            // 验证学生是否已选择该课程
            CourseSelection courseSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), homework.getCourse().getId());
            if (courseSelection == null || courseSelection.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "您未选择该课程或课程状态不正确");
                return result;
            }
            
            // 检查是否已经提交过该作业
            HomeworkSubmission existingSubmission = homeworkSubmissionService.getHomeworkSubmissionByHomeworkIdAndStudentId(homeworkId, currentStudent.getId());
            if (existingSubmission != null) {
                result.put("success", false);
                result.put("message", "您已经提交过该作业");
                return result;
            }
            
            // 验证提交内容
            if (content == null || content.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "作业内容不能为空");
                return result;
            }
            
            if (content.trim().length() > 2000) {
                result.put("success", false);
                result.put("message", "作业内容不能超过2000字");
                return result;
            }
            
            // 处理文件上传
            String fileUrl = null;
            if (file != null && !file.isEmpty()) {
                // 验证文件大小（20MB限制）
                if (file.getSize() > 20 * 1024 * 1024) {
                    result.put("success", false);
                    result.put("message", "文件大小不能超过20MB");
                    return result;
                }
                
                // 验证文件类型
                String originalFilename = file.getOriginalFilename();
                if (originalFilename != null) {
                    String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                    String[] allowedExtensions = {"pdf", "doc", "docx", "txt", "zip", "rar", "jpg", "jpeg", "png"};
                    boolean isValidExtension = false;
                    for (String ext : allowedExtensions) {
                        if (ext.equals(extension)) {
                            isValidExtension = true;
                            break;
                        }
                    }
                    
                    if (!isValidExtension) {
                        result.put("success", false);
                        result.put("message", "不支持的文件类型，请上传PDF、Word文档、文本文件、压缩包或图片");
                        return result;
                    }
                    
                    // 保存文件
                    fileUrl = saveUploadedFile(file, currentStudent.getId(), homeworkId);
                    if (fileUrl == null) {
                        result.put("success", false);
                        result.put("message", "文件上传失败，请重试");
                        return result;
                    }
                }
            }
            
            // 创建作业提交记录
            HomeworkSubmission submission = new HomeworkSubmission();
            submission.setHomework(homework);
            submission.setStudent(currentStudent);
            submission.setContent(content.trim());
            if (fileUrl != null) {
                submission.setFileUrl(fileUrl);
            }
            
            boolean addResult = homeworkSubmissionService.addHomeworkSubmission(submission);
            if (addResult) {
                result.put("success", true);
                result.put("message", "作业提交成功");
            } else {
                result.put("success", false);
                result.put("message", "作业提交失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "作业提交失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 保存上传的文件
     */
    private String saveUploadedFile(MultipartFile file, Long studentId, Long homeworkId) {
        try {
            // 获取Web应用的根目录
            String webAppRoot = System.getProperty("user.dir");
            String uploadBaseDir = webAppRoot + java.io.File.separator + "uploads" + java.io.File.separator + 
                                 "homework" + java.io.File.separator + studentId + java.io.File.separator + homeworkId;
            
            // 创建上传目录
            java.io.File uploadDir = new java.io.File(uploadBaseDir);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    System.err.println("Failed to create directory: " + uploadBaseDir);
                    return null;
                }
            }
            // 处理文件名，移除中文字符和特殊字符
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                originalFilename = "unnamed_file";
            }
            // 获取文件扩展名
            String extension = "";
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex > 0) {
                extension = originalFilename.substring(lastDotIndex);
            }
            // 生成安全的文件名（只包含数字、字母和下划线）
            String safeFilename = System.currentTimeMillis() + "_homework_" + studentId + "_" + homeworkId + extension;
            // 创建完整的文件路径
            java.io.File targetFile = new java.io.File(uploadDir, safeFilename);
            // 保存文件
            file.transferTo(targetFile);
            // 返回相对路径（用于存储到数据库）
            String relativePath = "uploads/homework/" + studentId + "/" + homeworkId + "/" + safeFilename;
            return relativePath;
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("File upload failed: " + e.getMessage());
            return null;
        }
    }

    /**
     * 删除作业提交
     */
    @PostMapping("/homework/delete")
    @ResponseBody
    public Map<String, Object> deleteHomework(@RequestParam Long submissionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 查询作业提交记录
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(submissionId);
            if (submission == null) {
                result.put("success", false);
                result.put("message", "作业提交记录不存在");
                return result;
            }
            
            // 验证权限 - 只能删除自己的作业提交
            if (!submission.getStudent().getId().equals(currentStudent.getId())) {
                result.put("success", false);
                result.put("message", "您没有权限删除该作业提交");
                return result;
            }
            
            // 如果作业已经评分，不允许删除
            if (submission.getScore() != null) {
                result.put("success", false);
                result.put("message", "该作业已评分，不能删除");
                return result;
            }
            
            // 删除作业提交记录
            boolean deleteResult = homeworkSubmissionService.deleteHomeworkSubmission(submissionId);
            if (deleteResult) {
                result.put("success", true);
                result.put("message", "作业提交删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败，请重试");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取指定课程的作业列表（Ajax请求）
     */
    @GetMapping("/homework/by-course/{courseId}")
    @ResponseBody
    public Map<String, Object> getHomeworksByCourse(@PathVariable Long courseId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 验证学生是否已选择该课程
            CourseSelection courseSelection = courseSelectionService.findByStudentIdAndCourseId(currentStudent.getId(), courseId);
            if (courseSelection == null || courseSelection.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "您未选择该课程");
                return result;
            }
            
            // 获取该课程的作业
            List<Homework> homeworks = homeworkService.getHomeworksByCourseId(courseId);
            List<Map<String, Object>> availableHomeworks = new ArrayList<>();
            
            if (homeworks != null) {
                for (Homework homework : homeworks) {
                    // 检查学生是否已经提交过该作业
                    HomeworkSubmission existingSubmission = homeworkSubmissionService.getHomeworkSubmissionByHomeworkIdAndStudentId(homework.getId(), currentStudent.getId());
                    if (existingSubmission == null) {
                        Map<String, Object> homeworkMap = new HashMap<>();
                        homeworkMap.put("id", homework.getId());
                        homeworkMap.put("title", homework.getTitle());
                        homeworkMap.put("content", homework.getContent());
                        homeworkMap.put("deadline", homework.getDeadlineStr());
                        availableHomeworks.add(homeworkMap);
                    }
                }
            }
            
            result.put("success", true);
            result.put("homeworks", availableHomeworks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取作业列表失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 下载作业文件
     */
    @GetMapping("/homework/download/{submissionId}")
    public ResponseEntity<Resource> downloadHomeworkFile(@PathVariable Long submissionId, HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return ResponseEntity.status(401).build();
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                return ResponseEntity.status(401).build();
            }
            
            // 获取作业提交记录
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(submissionId);
            if (submission == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 验证权限 - 只能下载自己的作业文件
            if (!submission.getStudent().getId().equals(currentStudent.getId())) {
                return ResponseEntity.status(403).build();
            }
            
            // 检查文件是否存在
            if (submission.getFileUrl() == null || submission.getFileUrl().trim().isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            // 构建绝对文件路径
            String webAppRoot = System.getProperty("user.dir");
            String absolutePath = webAppRoot + java.io.File.separator + submission.getFileUrl().replace("/", java.io.File.separator);
            
            java.io.File file = new java.io.File(absolutePath);
            if (!file.exists()) {
                System.err.println("File not found: " + absolutePath);
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(file);
            String filename = file.getName();
            
            // 处理文件名编码
            String encodedFilename = java.net.URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 考勤管理页面
     */
    @GetMapping("/attendance")
    public String studentAttendance(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "5") int size,
                                   @RequestParam(required = false) String courseNameSearch,
                                   Model model,
                                   HttpSession session) {
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                model.addAttribute("error", "无法获取学生信息，请联系管理员");
                return "student/attendance";
            }
            
            // 获取学生的所有考勤记录
            List<Attendance> allAttendances = attendanceService.getAttendancesByStudentId(currentStudent.getId().intValue());
            if (allAttendances == null) {
                allAttendances = new ArrayList<>();
            }
            
            // 如果有课程名称搜索条件，进行过滤
            List<Attendance> filteredAttendances = allAttendances;
            if (courseNameSearch != null && !courseNameSearch.trim().isEmpty()) {
                filteredAttendances = new ArrayList<>();
                for (Attendance attendance : allAttendances) {
                    if (attendance.getCourse() != null && 
                        attendance.getCourse().getName() != null && 
                        attendance.getCourse().getName().contains(courseNameSearch.trim())) {
                        filteredAttendances.add(attendance);
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredAttendances.size());
            List<Attendance> pageAttendances = new ArrayList<>();
            if (start < filteredAttendances.size()) {
                pageAttendances = filteredAttendances.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) filteredAttendances.size() / size);
            
            // 计算考勤统计信息（基于所有记录，不是过滤后的）
            Map<String, Integer> attendanceStats = calculateAttendanceStatistics(allAttendances);
            
            model.addAttribute("attendances", pageAttendances);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", filteredAttendances.size());
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("currentStudent", currentStudent);
            model.addAttribute("attendanceStats", attendanceStats);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("attendances", new ArrayList<>());
            model.addAttribute("currentPage", 1);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("courseNameSearch", courseNameSearch);
            model.addAttribute("attendanceStats", new HashMap<>());
            model.addAttribute("error", "加载考勤信息失败：" + e.getMessage());
        }
        
        return "student/attendance";
    }

    /**
     * 计算考勤统计信息
     */
    private Map<String, Integer> calculateAttendanceStatistics(List<Attendance> attendances) {
        Map<String, Integer> stats = new HashMap<>();
        stats.put("total", attendances.size());
        stats.put("present", 0);  // 正常
        stats.put("absent", 0);   // 缺勤
        stats.put("leave", 0);    // 请假
        stats.put("late", 0);     // 迟到
        stats.put("earlyLeave", 0); // 早退
        
        for (Attendance attendance : attendances) {
            if (attendance.getStatus() != null) {
                switch (attendance.getStatus()) {
                    case Attendance.STATUS_PRESENT:
                        stats.put("present", stats.get("present") + 1);
                        break;
                    case Attendance.STATUS_ABSENT:
                        stats.put("absent", stats.get("absent") + 1);
                        break;
                    case Attendance.STATUS_LEAVE:
                        stats.put("leave", stats.get("leave") + 1);
                        break;
                    case Attendance.STATUS_LATE:
                        stats.put("late", stats.get("late") + 1);
                        break;
                    case Attendance.STATUS_EARLY_LEAVE:
                        stats.put("earlyLeave", stats.get("earlyLeave") + 1);
                        break;
                }
            }
        }
        
        // 计算出勤率
        int totalValid = stats.get("total");
        int presentCount = stats.get("present") + stats.get("late") + stats.get("earlyLeave"); // 迟到、早退也算出勤
        if (totalValid > 0) {
            stats.put("attendanceRate", Math.round((float) presentCount / totalValid * 100));
        } else {
            stats.put("attendanceRate", 0);
        }
        
        return stats;
    }

    /**
     * 获取作业提交详情（Ajax请求）
     */
    @GetMapping("/homework/details/{submissionId}")
    @ResponseBody
    public Map<String, Object> getSubmissionDetails(@PathVariable Long submissionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的学生信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return result;
            }
            
            Student currentStudent = studentService.findByUserId(currentUser.getId());
            if (currentStudent == null) {
                result.put("success", false);
                result.put("message", "无法获取学生信息");
                return result;
            }
            
            // 获取作业提交详情
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(submissionId);
            if (submission == null) {
                result.put("success", false);
                result.put("message", "作业提交记录不存在");
                return result;
            }
            
            // 验证权限 - 只能查看自己的作业提交
            if (!submission.getStudent().getId().equals(currentStudent.getId())) {
                result.put("success", false);
                result.put("message", "您没有权限查看该作业提交");
                return result;
            }
            
            result.put("success", true);
            result.put("data", submission);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取作业详情失败：" + e.getMessage());
        }
        
        return result;
    }
} 